import { Service } from 'egg';

export default class LoginService extends Service {

    public async loginByOpenID(openid: string, avatar?: string) {
        const { service } = this;
        // 通过openId查找数据库中对应的用户
        let user = await service.db.user.findOneByOpenid(openid);
        // 如果用户不存
        if (!user) {
            this.ctx.helper.unauth();
        }
        if (avatar) {
            // 更新用户头像
            user = await service.db.user.updateUser(user!.id, { avatar });
        }

        // 找到用户后，返回jwt
        const token = this.generateJwt(user!.id);
        return { token, user};
    }

    private generateJwt(userId: number) {
        const jwtSecret = this.ctx.app.config.jwt.secret;
        const token = this.ctx.app.jwt.sign({
            userId,
        }, jwtSecret, {
            expiresIn: '30d',
        });
        return token;
    }
}
